package com.hbhmzy.utils;

import android.content.Context;
import android.content.Intent;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;


import static com.hbhmzy.call.WantCallFragment.name;
import static com.hbhmzy.call.WantCallFragment.symbol;
import static com.hbhmzy.call.WantCallFragment.targetname;

/**
 * 读取服务器返回的响应信息
 *
 * @author zhb
 */
public class ClientHandler extends ChannelInboundHandlerAdapter  {
    private Context context;
    public ClientHandler(Context context){
        this.context=context;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        try {
            ByteBuf bb = (ByteBuf) msg;
            byte[] respByte = new byte[bb.readableBytes()];
            bb.readBytes(respByte);
            String respStr = new String(respByte, "utf8");
            String str =respStr.substring(respStr.length()-3,respStr.length());
            Log.e("ArrivebyTCP", respStr);
            if(str.equals("ect")){
                //拒绝 reject
                Intent intent2=new Intent("hbhmzy.reject");
                context.getApplicationContext().sendBroadcast(intent2);
            }else if(str.equals("art")){
                //发送广播通知 有电话等待接听 start
                targetname = respStr.substring(0,11);//获取前11位作为 目标号码。
                symbol = name + "#" + targetname + ":";
                Intent intent=new Intent("hbhmzy.start");
                context.getApplicationContext().sendBroadcast(intent);
            }else if(str.equals("acc")){
                Intent intent1=new Intent("hbhmzy.acc");
                context.getApplicationContext().sendBroadcast(intent1);
            }else if (str.equals("ine")){
                //离线 offline
                Intent intent3=new Intent("hbhmzy.offline");
                context.getApplicationContext().sendBroadcast(intent3);
            }

        } finally {
            // 必须释放msg数据
            ReferenceCountUtil.release(msg);
        }

    }


    // 数据读取完毕的处理
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        System.out.println("客户端读取数据完毕");
    }

    // 出现异常的处理
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("client 读取数据出现异常");
        ctx.close();
    }

}